import api from "../../utils/api"
import Utils from "../../utils/utils"

let countdownTimer: number;// 倒计时定时器
let timer: number; //倒计时结束延迟一秒调接口
// pages/orderdetail/orderdetail.ts
Page({

  /**
   * 页面的初始数据
   */
  data: {
    type: 99 as number,//99-未支付，0-待发货, 1-已发货, 2-已完成, 3-已取消, 4-售后处理中, 5-已退款, 6-已同意退货,7-已退回
    order: [
      {
        status: '待发货',
        tips: "已收到您的货款，我们会尽快发货",
        text: 'waitSend',
        value: ["WAITING_SEND", "DELIVERY_LOCKED", "REFUND_REJECTED", "REDELIVERY_LOCKED"]
      },
      {
        status: '商品已发出',
        tips: "商品正在运送中,请耐心等待",
        text: 'send',
        value: ["DELIVERING", "DELIVERING_NO_RETURN", "REDELIVERING"]
      },
      {
        status: '订单已完成',
        tips: "订单已完成,如有问题请联系客服",
        text: 'done',
        value: ["FINISHED"]
      },
      {
        status: '订单已取消',
        tips: "订单已取消,如有问题请联系客服",
        text: 'cancel',
        value: ["CANCELED", "CANCELED_REFUND"]
      },
      {
        status: '售后处理中',
        tips: "订单正在售后处理中",
        text: 'service',
        value: ["RETURN_APPLIED"]
      },
      {
        status: '已退款',
        tips: "已退款 退款金额 ",
        text: 'refund',
        value: ["REFUND_FINISHED"]
      },
      {
        status: "已同意退货",
        tips: "请及时提交退回信息",
        text: "agree",
        value: ["RETURN_AGREED"]
      },
      {
        status: '售后处理中',
        tips: "订单正在售后处理中",
        text: 'service-send',
        value: ["RETURN_SENT"]
      },
    ],
    id: undefined as number | undefined,//订单ID
    orderInfo: {} as OrderModel,//订单信息
    orderContents: [] as OrderContentModel[],//商品信息
    time: [] as Array<String>,//倒计时信息
    pay: "0" as string,// 是否是立即支付,如果是就自动调支付接口
  },
  // 获取订单详情
  getOrderDetail(id: number): void {
    const { order } = this.data
    api.order.getOrderDetail({ id }).then(res => {
      if (res.data.code == '000') {
        // 先根据状态设置页面展示
        const list = res.data.data
        let time
        if (list) {
          const index = order.findIndex(item => {
            return item.value.includes(list.status)
          })
          this.setData({
            type: index == -1 ? 99 : index
          })
          // 数据转换
          list.commodityAmount = Utils.priceToYuan(list.commodityAmount as number)
          list.couponAmount = Utils.priceToYuan(list.couponAmount as number)
          list.orderTime = Utils.timestampToDateTime(list.orderTime as number)
          // 待支付的启动倒计时
          if (list.status == "PAYING") {
            time = Utils.convertSeconds(list.paymentCountdown as number)
            this.beginTime(list.paymentCountdown as number)
          }
          list.totalAmount = Utils.priceToYuan(list.totalAmount as number)
          list.shippingCost = Utils.priceToYuan(list.shippingCost as number)
          if (list.orderContents) {
            list.orderContents.forEach(item => {
              item.price = Utils.priceToYuan(item.price as number)
              item.couponAmount = Utils.priceToYuan(item.couponAmount as number)
            })
            this.setData({
              orderContents: list.orderContents
            })
          }
          this.setData({
            orderInfo: list,
            time,
          })
        }
      } else {
        wx.showToast({
          title: res.data.message as string,
          icon: "error"
        })
      }
    })
  },
  // 启动倒计时
  beginTime(second: number): void {
    if (countdownTimer) {
      clearInterval(countdownTimer);
    }
    if (timer) {
      clearTimeout(timer);
    }
    countdownTimer = setInterval(() => {
      second--;
      if (second < 0) {
        clearInterval(countdownTimer);
        timer = setTimeout(() => {
          this.getOrderDetail(this.data.id as number)
        }, 1000)
      } else {
        this.setData({
          time: Utils.convertSeconds(second)
        })
      }
    }, 1000);
  },
  // 确认取消订单
  confirmCancel(e: any): void {
    const { type } = this.data
    // 待支付---直接掉接口
    const params: OrderCancelOrderParam = {
      id: this.data.id,
      reason: e.detail.reason
    }
    api.order.cancelOrder(params).then(res => {
      if (res.data.code == "000") {
        this.setData({
          type: 3
        })
      } else {
        wx.showToast({
          title: res.data.message as string,
          icon: "error"
        })
      }
    })
  },
  // 支付订单
  toPay(): void {
    try {
      const { id } = this.data
      api.order.getClientPayParam({ id }).then(res => {
        if (res.data.code == "000") {
          const params = JSON.parse(res.data.data as string)
          wx.requestPayment({
            ...params,
            success: () => {
              // 清除定时器
              clearInterval(countdownTimer)
              // 重新请求订单
              this.getOrderDetail(id as number);
            },
            complete: () => {
              this.setData({
                pay: "0"
              })
            }
          })
        } else {
          wx.showToast({
            title: res.data.message as string,
            icon: "error"
          })
        }
      })
    } catch (error) {
      console.error("JSON.parse error")
    }
  },
  // 跳转到退款信息页面
  toRefundDetail(): void {
    const data = JSON.stringify(this.data.orderInfo)
    wx.navigateTo({
      url: "/pages/refund/refund?data=" + data
    })
  },
  // 查看物流
  toLogistics(): void {
    wx.navigateTo({
      url: "/pages/logisticsdetail/logisticsdetail?type=order&id=" + this.data.id
    })
  },
  // 寄回货物
  sendGoods(e: any): void {
    const { id } = this.data
    const { shipCompany, shipNo } = e.detail
    const params = {
      id,
      shipCompany,
      shipNo
    }
    api.order.sendBackOrder(params).then(res => {
      if (res.data.code == "000") {
        this.getOrderDetail(id as number)
      } else {
        wx.showToast({
          title: res.data.message as string,
          icon: "error"
        })
      }
    })
  },
  // 确认收货
  complete(): void {
    console.log(this.data.orderInfo);
    let _this: any = this;
    if(this.data.orderInfo.payType === 'WECHAT_PAY'){
      if ((wx as any).openBusinessView) {
        (wx as any).openBusinessView({
          businessType: 'weappOrderConfirm',
          extraData: {
            merchant_id: this.data.orderInfo.wxPayMerchantId,
            merchant_trade_no: this.data.orderInfo.wxPayOutTradeNo,
          },
          success() {
            const { id, pay } = _this.data
            _this.getOrderDetail(id as number)
            if (pay == '1') {
              _this.toPay();
            }
          },
          fail(e: any) {
            console.log(e);
          },
        });
      } else {
        wx.showModal({
          showCancel:false,
          content:'您的微信版本过低，请升级微信客户端版本'
        });
      }
      return;
    }
    this.confirmReceive();
  },
  confirmReceive(): void {
    const { id } = this.data
    api.order.confirmReceiveOrder({ id }).then(res => {
      if (res.data.code == "000") {
        this.getOrderDetail(id as number)
      } else {
        wx.showToast({
          title: res.data.message as string,
          icon: "error"
        })
      }
    })
  },
  // 取消申请
  cancelRefund(): void {
    const { id } = this.data
    api.order.cancelReturnApply({ id }).then(res => {
      if (res.data.code == "000") {
        this.getOrderDetail(id as number)
      } else {
        wx.showToast({
          title: res.data.message as string,
          icon: "error"
        })
      }
    })
  },
  delete(): void {
    const { id } = this.data
    api.order.deleteOrder({ id }).then(res => {
      if(res.data.code == "000") {
        wx.navigateBack();
      }else {
        wx.showToast({
          title: res.data.message as string,
          icon:"error"
        })
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options: any) {
    const id = Number(options.id)
    this.setData({
      id
    })
    if (options.pay) {
      this.setData({
        pay: options.pay
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    const { id, pay } = this.data
    this.getOrderDetail(id as number)
    if (pay == '1') {
      this.toPay();
    }
  },
})